package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 恒通易信
 * 账号
 * 验证码产品编码：1012818
 * 通知产品编码：1012808
 * 营销产品编码：1012812
 */
public class SmsApiHTYXv5 extends GateWayHttpAbstract
{

    public SmsApiHTYXv5(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid", paramsMaps.get("userid"));//编码GBK,UTF-85
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("password")).toUpperCase());

        params.put("phone", mt.getPhone());
        params.put("codetype", paramsMaps.get("codetype"));//编码GBK,UTF-85
        params.put("message", Base64.encodeBase64String(mt.getSmsContent().getBytes()));
        params.put("encodeway", paramsMaps.get("encodeway"));//加密方式base64

        String json =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/protocol/sendMessage.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("网关v5:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        List<SMSSRMessage> resultList = Lists.newArrayList();
        String result = "qx" + json;
        SMSSRMessage message = initGatewayResultMessage(result, mt, "qx");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;

        if(StringUtils.equals(message.getResult(), "F10199")) {
            resultCode = "0";
            if (json.length() > 10) {
                taskid = json;
                resultMessage = "sucesss";
            } else {
                resultCode = json;
                resultMessage = json + "error";
            }
            message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
        }

        resultList.add(message);
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        logger.info("{}网关推送状态报告v3:{}", gateWayID, text);

        	if(StringUtils.isNotBlank(text)) {
        	    try{
                    text = URLDecoder.decode(text.substring(4), "utf-8");
                } catch (Exception e) {
        	        e.printStackTrace();
                    return new SmsHttpMsgResponse("-1");
                }
                String[] arrays = text.split(";");
                for (int i = 0; i < arrays.length; i++) {
                    String[] data = arrays[i].split(",");
                    String code = data[5];
                    if (StringUtils.equals(code,"0")) {
                        code = "DELIVRD";
                    }
                    SMSRTMessage smsRtMessage = initSmsRtMessage(data[4], data[3],data[3],
                            code, "DELIVRD");
                    rtList.add(smsRtMessage);
                }
        	}
        return new SmsHttpMsgResponse("0");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
    	logger.info("{}网关推送用户上行v3:{}", gateWayID, text);
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        String[] arrays = text.substring(4).split(";");
        if (arrays != null & arrays.length > 0) {
            try {
                for (int i = 0; i < arrays.length; i++) {
                    String[] data = arrays[i].split(",");
                    SMSMOMessage sMSMOMessage = new SMSMOMessage();
                    sMSMOMessage.setGateWayID(gateWayID);
                    sMSMOMessage.setMsgContent(URLDecoder.decode(data[4],"utf-8"));
                    sMSMOMessage.setMsgid(data[3]);
                    sMSMOMessage.setPhone(data[3]);
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                    sMSMOMessage.setUuid(UUID.randomUUID().toString());
                    moList.add(sMSMOMessage);
                }
            }catch (UnsupportedEncodingException e) {
                logger.error("{}网关推送用户上行解析错误:{}", gateWayID, text);
                e.printStackTrace();
            }
        }

        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("userid",paramsMaps.get("userid"));
        params.put("password",DigestUtils.md5Hex(paramsMaps.get("password")).toUpperCase());
        String apiUrl = paramsMaps.get("apiUrl");
        String result =  HttpRequest.sendGet(apiUrl + "/protocol/selectBalance.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
       if (!Strings.isNullOrEmpty(result)) {
           return result;
       }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
    /*	SmsApiZHAOYONGSMS api = new SmsApiZHAOYONGSMS("JIESMS", "{\"account\":\"lihua\",\"password\":\"llh@9988\",\"longSms\":\"\",\"apiUrl\":\"http://www.88dx.cn\",\"reportSecTime\":\"5\", \"deliverSecTime\":\"5\"}");
    	SMSMTMessage mt = new SMSMTMessage();
    	mt.setPhone("18268846802");
    	mt.setSmsContent("【千橡科技】验证码：123456，10分钟内有效，如非本人操作，请忽略！");
    	List<SMSSRMessage> list = api.doSend(mt);
    	System.out.println(JSON.toJSONString(list));*/
//        String params = "{\"userid\":\"975\",\"account\":\"yhkjjr\",\"password\":\"yhkjjr@2018\",\"apiUrl\":\"https://sms.xinxiguanjia.com/sms.aspx/\"}";
//        String params = "{\"userid\":\"101089\",\"password\":\"Zykj0312\",\"apiUrl\":\"http://api.hengtongexun.com:8090\",\"codetype\":\"utf-8\",\"encodeway\":\"base64\"}";
//        SmsApiHTYX api = new SmsApiHTYX("ZY",params);
////        String balance = api.balance();
////        System.out.println("balance"+balance);
//        SMSMTMessage message = new SMSMTMessage();
//        message.setPhone("18268846802");
//        message.setId("11111111");
//        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
        String aa = "par=901846%2C101089%2C1234%2C18268846802%2C263221537553733%2CJL%3A0029%2C2018-03-22+15%3A37%3A57";
//        api.parseReport(aa, Lists.<SMSRTMessage>newArrayList());
//        System.out.println(balance);
        String a = "123456";
        String s = Base64.encodeBase64String(a.getBytes()).toLowerCase();
        System.out.println(s);
    }
}